package netty.decoder.delimiterbasedframedecoder.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

public class EchoClient {
	public void connect(String host, int port){
		
		EventLoopGroup workGroup = new NioEventLoopGroup();
		
		Bootstrap clientStrap = new Bootstrap();
		
		clientStrap.group(workGroup).option(ChannelOption.TCP_NODELAY, true)
		.channel(NioSocketChannel.class)
		.handler(new ChannelInitializer<Channel>() {

			@Override
			protected void initChannel(Channel ch) throws Exception {
				ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
				ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, delimiter));
				ch.pipeline().addLast(new StringDecoder());
				ch.pipeline().addLast(new EchoClientHandler());
				
				
			}
		});
		try{
			ChannelFuture f = clientStrap.connect(host, port).sync();
			f.channel().closeFuture().sync();
		} catch (Exception e){
			e.printStackTrace();
		} finally{
			workGroup.shutdownGracefully();
		}
	}
	
	public static void main(String []args){
		new EchoClient().connect("127.0.0.1", 8080);
	}
}
